<template>
    <el-dialog
      :model-value="modelValue"
      :title="$t('msg.excel.roleDialogTitle')"
      width="60%"
      @close="handleColse"
    >
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          :label="item.title"
          v-for="item in allRoleList"
          :key="item.id"
        />
      </el-checkbox-group>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleColse">{{
            $t('msg.universal.cancel')
          }}</el-button>
          <el-button type="primary" @click="handleConfirm">
            {{ $t('msg.universal.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </template>
   
  <script setup>
  import { defineProps, defineEmits, ref, watch } from 'vue'
  import {
    getRoleListAction,
    getCurrentRoleAction,
    updateRoleAction
  } from '@/apis/user'
   
  import { ElMessage } from 'element-plus'
  import { useI18n } from 'vue-i18n'
  const props = defineProps({
    modelValue: {
      type: Boolean,
      required: true
    },
    userId: {
      type: String,
      required: true
    }
  })
   
  const emits = defineEmits(['update:modelValue', 'updateRole'])
  const handleColse = () => {
    emits('update:modelValue', false)
  }
   
  const i18n = useI18n()
  const handleConfirm = async () => {
    handleColse()
    const roles = checkList.value.map((title) => {
      return allRoleList.value.find((item) => item.title === title)
    })
    await updateRoleAction(props.userId, roles)
    ElMessage.success(i18n.t('msg.role.updateRoleSuccess'))
    emits('updateRole')
  }
   
  const checkList = ref([])
  const allRoleList = ref([])
   
  // 获取所有的角色信息
  const getRoleList = async () => {
    allRoleList.value = await getRoleListAction()
  }
  getRoleList()
   
   
  // 获取当前账户的角色信息
  const getCurrentRole = async () => {
    const { role } = await getCurrentRoleAction(props.userId)
    checkList.value = role.map((item) => item.title)
  }
   
  // 监听 当userId变化时 再触发getCurrentRole
  watch(
    () => props.userId,
    (newVal) => {
      if (newVal) getCurrentRole()
    }
  )
  </script>
   
  <style lang="scss" scoped></style>